// NEW FILE: java/com/miui/theme/custom/screen/TableDetailsScreen.kt
package com.miui.theme.custom.screen

import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.lazy.LazyColumn
import androidx.compose.foundation.lazy.items
import androidx.compose.material3.*
import androidx.compose.runtime.*
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.text.style.TextAlign
import com.miui.theme.custom.components.AppTopAppBar
import com.miui.theme.custom.navigation.currentComposeNavigator
import com.miui.theme.custom.viewmodel.ColumnInfo
import com.miui.theme.custom.viewmodel.DataState
import com.miui.theme.custom.viewmodel.TableDetailsViewModel
import org.koin.androidx.compose.koinViewModel

@Composable
fun TableDetailsScreen(
    tableName: String,
    viewModel: TableDetailsViewModel = koinViewModel()
) {
    val navigator = currentComposeNavigator
    val dataState by viewModel.dataState.collectAsState()
    val columnsInfo by viewModel.columnsInfo.collectAsState()
    val error by viewModel.error.collectAsState()

    LaunchedEffect(tableName) {
        viewModel.loadTableStructure(tableName)
    }

    Scaffold(
        topBar = {
            AppTopAppBar(
                title = "表结构: $tableName",
                onNavigateUp = { navigator.navigateUp() }
            )
        }
    ) { padding ->
        Box(
            modifier = Modifier
                .fillMaxSize()
                .padding(padding),
            contentAlignment = Alignment.Center
        ) {
            when (dataState) {
                DataState.Loading -> CircularProgressIndicator()
                DataState.Error -> Text(
                    "加载失败: $error",
                    color = MaterialTheme.colorScheme.error,
                    textAlign = TextAlign.Center
                )
                DataState.Success -> {
                    LazyColumn(modifier = Modifier.fillMaxSize()) {
                        items(columnsInfo) { info ->
                            ColumnInfoItem(info)
                            HorizontalDivider()
                        }
                    }
                }
                else -> {}
            }
        }
    }
}

@Composable
private fun ColumnInfoItem(info: ColumnInfo) {
    ListItem(
        headlineContent = { Text(info.field, style = MaterialTheme.typography.titleMedium) },
        supportingContent = {
            Column {
                Text("Type: ${info.type}")
                Text("Key: ${info.key.ifBlank { "N/A" }}")
                Text("Nullable: ${info.isNull}")
                Text("Default: ${info.default ?: "NULL"}")
                Text("Extra: ${info.extra.ifBlank { "N/A" }}")
            }
        }
    )
}